use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::tags::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub slug: Option<String>,
    pub position: i32,
    pub active: bool,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Slug must not be empty."))]
    pub slug: Option<String>,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            slug: self.slug.as_ref().clone(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::tags::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a tag by the provided id
    ///
    /// # Errors
    ///
    /// When could not find tag or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let tag = tags::Entity::find()
            .filter(model::query::condition().eq(tags::Column::Id, id).build())
            .one(db)
            .await?;
        tag.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds a tag by the provided slug
    ///
    /// # Errors
    ///
    /// When could not find tag or DB query error
    pub async fn find_by_slug(db: &DatabaseConnection, slug: &str) -> ModelResult<Self> {
        let tag = tags::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tags::Column::Slug, slug)
                    .build(),
            )
            .one(db)
            .await?;
        tag.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// Asynchronously creates a tag and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the tag into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let tag = tags::ActiveModel {
            slug: ActiveValue::set(params.slug.clone()),
            position: ActiveValue::set(params.position),
            active: ActiveValue::set(params.active),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(tag)
    }

    /// Deletes the tag
    ///
    /// # Errors
    ///
    /// When could not delete the tag from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: tags::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the tag's active status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_active_status(
        mut self,
        db: &DatabaseConnection,
        active: bool,
    ) -> ModelResult<Model> {
        self.active = ActiveValue::set(active);
        Ok(self.update(db).await?)
    }

    /// Updates the tag's position
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_position(
        mut self,
        db: &DatabaseConnection,
        position: i32,
    ) -> ModelResult<Model> {
        self.position = ActiveValue::set(position);
        Ok(self.update(db).await?)
    }

    /// Updates the tag's slug
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_slug(
        mut self,
        db: &DatabaseConnection,
        slug: Option<String>,
    ) -> ModelResult<Model> {
        self.slug = ActiveValue::set(slug);
        Ok(self.update(db).await?)
    }
}
